<?php

namespace App\Console\Commands;

use App\Models\Common\Common;
use App\Models\Tools\Data;
use App\Models\Tools\Period;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ExploreAcceptance extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:explore_acceptance';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '验收超时,自动验收通过';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $overtimes = Period::getSetting('EXPLORE_ACCEPTANCE_OVERTIME');
        try {
            DB::beginTransaction();
            // 检查待审核状态超过规定审核时间的工单

            $works = DB::table('explore_work as ew')
                ->leftJoin('shop', 'ew.shop_id', '=', 'shop.shop_id')
                ->leftJoin('lottery_users as lu1','ew.apply_we_id','=','lu1.we_id')
                ->leftJoin('lottery_users as lu2', 'ew.receiver_we_id', '=', 'lu2.we_id')
                ->leftJoin('talent','lu2.we_id','=','talent.we_id')
                ->where('ew.status', '=', Data::DATA_DB_EXPLORE_WORK_STATUS_SUBMIT)// 已投稿
                ->where('ew.submit_time', '<', date('Y-m-d H:i:s', time() - $overtimes))
                ->lockForUpdate()
                ->select('ew.work_id', 'ew.work_no', 'shop.shop_name','lu1.openid as apply_openid', 'lu2.openid as receiver_openid','talent.account_name')
                ->get();

            if (!$works->count()) { // 如果没有待审核工单，结束本次定时任务
                DB::rollBack();
                return;
            }

            $work_ids = $works->pluck('work_id')->toArray();
            $works = $works->toArray();
            $works = json_decode(json_encode($works), true);

            // 自动审核通过
            DB::table('explore_work')
                ->whereIn('work_id', $work_ids)
                ->update([
                    'status' => Data::DATA_DB_EXPLORE_WORK_STATUS_ACCEPTED,
                    'accept_time' => date('Y-m-d H:i:s'),
                    'accept_remark' => '验收超时自动审核通过',
                ]);

            $log_arr = [];
            foreach ($works as $work) {
                $log_arr[] = [
                    'work_id' => $work['work_id'],
                    'action' => Data::DATA_DB_EXPLORE_WORK_ACTION_ACCEPTED,
                    'remark' => '店主验收超时，系统自动验收投稿',
                ];
            }
            // 记录日志
            DB::table('explore_work_log')->insert($log_arr);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::emergency(ExploreAcceptance::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'works' => $works ?? null]);
            return;
        }

        try {
            foreach ($works as $work) {
                // 发送验收微信通知（发送给达人）
                $data = [
                    'first' => '您在店铺【' . $work['shop_name'] . '】的投稿已被系统自动验收',
                    'keyword1' => $work['work_no'],
                    'keyword2' => date('Y-m-d H:i:s'),
                    'keyword3' => '验收已通过',
                    'keyword4' => '系统自动验收',
                    'keyword5' => '来飞网',
                ];
                //发送通知
                Common::sendLaifeiMessage($work['receiver_openid'], 'work_check', $data, '/talent/history?tab=1');

                // 发送验收微信通知（发送给商家）
                $data = [
                    'first' => '达人【'.$work['account_name'].'】在您的店铺【' . $work['shop_name'] . '】的投稿验收超时，已被系统自动验收',
                    'keyword1' => $work['work_no'],
                    'keyword2' => date('Y-m-d H:i:s'),
                    'keyword3' => '验收已通过',
                    'keyword4' => '系统自动验收',
                    'keyword5' => '来飞网',
                    'remark' => [
                        'value' => '您未在达人提交投稿后的48小时内验收投稿，此投稿已自动验收通过。',
                        'color' => '#F00'
                    ],
                ];
                //发送通知
                Common::sendLaifeiMessage($work['apply_openid'], 'work_check', $data, '/history?tab=1');
            }
        } catch (\Exception $e) {
            Log::error(ExploreAcceptance::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'works' => $works]);
        }
        return;
    }
}
